import React, { PureComponent } from 'react';
import { Button, Card, Checkbox, message, Modal, Tabs } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect } from 'dva';
import _ from 'lodash';
import ProjectsPath from '@/components/ProjectsPath';
import PageEmpty from '@/components/PageEmpty';
import { router } from 'umi';
import * as apis from '@/services/ValueApprovelMgr';
import * as api from '@/services/ReturnMoneyPlanMgr';
import { commonBudgetVersion, commonCreateBudgetVerify } from '@/services/ContractPlanMgr';
import qs from 'qs';
import PageTop from './components/PageTop';
import { showConfirm } from '@/utils/utils';
import { PageExtra, TabBarExtraContent } from './components/Operation';
import CurrentStage from './components/CurrentStage';
import { BaseTable } from '@/components/BaseTable';
import TextScroll from '../../ContractPlan/VersionDetail/components/TextScroll';
import { getTitleTree, getFixedColumns, headerRenderer } from './utils/publicMethod';
import { handlerMatomoEvent } from '@/utils/matomo';
import AuthorizedButton from '@/components/AuthorizedButton';
import moment from 'moment';

const versionType = {
  dynamic: '月度动态版',
  budget: '预算版',
  strategy: '战规版',
  investment: '投资版',
};

// 分期回款计划
@connect(state => ({
  ...state.ReturnMoneyPlan,
  orgStructure: state.orgStructure,
}))
export default class IndexPage extends PureComponent {
  state = {
    emptyMsg: '版本不存在，请先创建新版本',
    unusualLoading: false,
    createLoading: false,
    deleteLoading: false,
    assessmentLoading: false,
    viewApprovedLoading: false,
    setBudgetLoading: false,
    visible: false,
    agentInfo: [],
  };

  componentDidMount() {
    // 初始化请求版本列表
    this.getVersionsList(this.props);
    // 初始化待办信息
    this.handlerAgentInfo(this.props.match.params);
    // 是否有版本 有则加载表格数据
    const isVersion = this.props.match.params.version;
    if (isVersion) this.getAllYearsList(this.props);
  }

  componentWillReceiveProps(nextProps) {
    // 切换分期类型 =>加载版本号
    const switchStage = this.props.match.params.stage !== nextProps.match.params.stage;
    // 切换版本类型 =>加载版本号
    const switchCategory = this.props.match.params.category !== nextProps.match.params.category;
    // 切换版本号 => 加载年月列表
    const switchVersion = this.props.match.params.version !== nextProps.match.params.version;
    // 切换年份 => 加载表格列表
    const switchYear = nextProps.currentYear !== this.props.currentYear;
    // 切换月份 => 加载表格header
    if (switchStage || switchCategory) {
      this.getVersionsList(nextProps);
      this.handlerAgentInfo(nextProps.match.params);
    }
    if (nextProps.match.params.version && switchVersion) {
      this.getAllYearsList(nextProps);
      this.handlerAgentInfo(nextProps.match.params);
    }
    if (nextProps.match.params.version && nextProps.currentYear && switchYear) {
      this.getTableList(nextProps);
    }
  }

  // 请求表格数据
  getTableList = props => {
    const self = this;
    const { dispatch, match, currentYear } = props;
    this.setState({ emptyMsg: '' });
    const params = {
      versionId: match.params.version || '',
      year: currentYear || '',
    };
    dispatch({
      type: 'ReturnMoneyPlan/getTableList',
      payload: { params },
      callback: () => self.setState({ emptyMsg: '列表数据不存在' }),
    });
  };

  // 请求年份列表
  getAllYearsList = props => {
    const self = this;
    const { dispatch, match } = props;
    const params = {
      versionId: match.params.version || '',
    };
    dispatch({
      type: 'ReturnMoneyPlan/getAllYearsList',
      payload: { params },
      callback: () => self.setState({ emptyMsg: '版本不存在，请先创建新版本' }),
    });
  };

  // 请求版本列表数据
  getVersionsList = props => {
    this.setState({ emptyMsg: '' });
    const { dispatch, match } = props;
    const self = this;
    // 获取versions
    dispatch({
      type: 'ReturnMoneyPlan/getVersionsList',
      payload: { match },
      callback: () => self.setState({ emptyMsg: '版本不存在，请先创建新版本' }),
    });
  };

  // 实时查询 签约门户待办信息
  handlerAgentInfo = obj => {
    const self = this;
    self.setState({
      agentInfo: [],
    });
    const params = {
      combinationId: `${obj.stage}${obj.category}`,
    };
    api.getPortalTodoUsingGET({ params }).then(result => {
      const condition = result && result.code === 1 && !_.isEmpty(result.data);
      if (condition) {
        self.setState({
          agentInfo: [result.data],
        });
      }
    });
  };

  // 异常创建版本
  handlerUnusualCreate = () => {
    const self = this;
    const { stage, category, project } = this.props.match.params;
    let budgetLabelOptions = []; // 预算版标签容器
    let budgetLabelValue = []; // 预算版标签默认选中的值
    // 请求异常创建版本
    const requestCreateVersion = versionIdentify => {
      const params = {
        stageId: stage,
        versionType: category,
        versionIdentify,
      };
      api
        .exceptionCreateUsingPOST({ data: params })
        .then(res => {
          if (res && res.code === 1) {
            message.loading('版本创建中', 1, () => {
              self.getVersionsList(self.props);
            });
          }
        })
        .then(() => {
          self.setState({
            unusualLoading: false,
            visible: false,
          });
        });
    };
    commonBudgetVersion({})
      .then(res => {
        if (res?.code === 1 && !_.isEmpty(res.data)) {
          budgetLabelOptions = [{ label: res.data, value: res.data }];
          budgetLabelValue = [_.head(budgetLabelOptions).value];
        }
      })
      .then(() => {
        // 弹出确认框
        showConfirm(
          () => {
            self.setState({
              unusualLoading: true,
            });
            // 如果有选中的预算版标签-校验是否可以创建
            if (!_.isEmpty(budgetLabelValue)) {
              commonCreateBudgetVerify({
                params: {
                  projectId: project,
                  stageId: stage,
                  type: 'return',
                },
              }).then(res1 => {
                if (res1.code === 1 && res1.data === 'ok') {
                  requestCreateVersion(_.head(budgetLabelValue));
                } else {
                  self.setState({
                    unusualLoading: false,
                  });
                }
              });
            } else {
              requestCreateVersion('');
            }
          },
          `确认新建${versionType[category]}回款计划异常版本吗？`,
          <>
            <div>创建回款计划异常版本将从最新审批通过的签约计划版本创建。</div>
            <Checkbox.Group
              options={budgetLabelOptions}
              defaultValue={budgetLabelValue}
              onChange={checkedValue => {
                budgetLabelValue = checkedValue;
              }}
            />
          </>,
        );
      });
  };

  // 创建版本
  handlerCreate = () => {
    const self = this;
    let budgetLabelOptions = []; // 预算版标签容器
    let budgetLabelValue = []; // 预算版标签默认选中的值
    const { stage, category, project } = this.props.match.params;
    // 请求创建版本
    const requestCreateVersion = versionIdentify => {
      const params = {
        stageId: stage,
        versionType: category,
        versionIdentify,
      };
      api
        .createUsingPOST_1({ data: params })
        .then(res => {
          if (res && res.code === 1) {
            message.loading('版本创建中', 1, () => {
              self.getVersionsList(self.props);
            });
          }
        })
        .then(() => {
          self.setState({
            createLoading: false,
            visible: false,
          });
        });
    };
    commonBudgetVersion({})
      .then(res => {
        if (res?.code === 1 && !_.isEmpty(res.data)) {
          budgetLabelOptions = [{ label: res.data, value: res.data }];
          budgetLabelValue = [_.head(budgetLabelOptions).value];
        }
      })
      .then(() => {
        api
          .createSourceDataUsingGET({
            params: {
              stageId: stage,
              versionType: category,
            },
          })
          .then(res => {
            if (res && res.code === 1) {
              const content = (
                <>
                  <div>将基于以下信息新建：</div>
                  <div>1、签约计划版本：{res.data.signPlanVersionName}；</div>
                  <div>2、回款系数版本：{res.data.returnCoefficientName}；</div>
                  <div>3、营销数据取数：{res.data.projectFetchNumberName}；</div>
                  <Checkbox.Group
                    options={budgetLabelOptions}
                    defaultValue={budgetLabelValue}
                    onChange={checkedValue => {
                      budgetLabelValue = checkedValue;
                    }}
                  />
                </>
              );
              // 弹出确认框
              showConfirm(
                () => {
                  self.setState({
                    createLoading: true,
                  });
                  // 如果有选中的预算版标签-校验是否可以创建
                  if (!_.isEmpty(budgetLabelValue)) {
                    commonCreateBudgetVerify({
                      params: {
                        projectId: project,
                        stageId: stage,
                        type: 'return',
                      },
                    }).then(res1 => {
                      if (res1.code === 1 && res1.data === 'ok') {
                        requestCreateVersion(_.head(budgetLabelValue));
                      } else {
                        self.setState({
                          createLoading: false,
                        });
                      }
                    });
                  } else {
                    requestCreateVersion('');
                  }
                },
                `确认新建${versionType[category]}回款计划吗？`,
                content,
              );
            }
          });
      });
  };

  // 删除版本
  handlerDelete = () => {
    const self = this;
    const { version, category } = self.props.match.params;
    showConfirm(
      () => {
        self.setState({ deleteLoading: true });
        api.delUsingDELETE_1({ params: { versionId: version } }).then(res => {
          if (res && res.code === 1) {
            message.loading('版本删除中', 2, () => {
              self.getVersionsList(self.props);
            });
          }
          self.setState({ deleteLoading: false });
        });
      },
      `确认删除${versionType[category]}的当前版本的回款计划吗？`,
      '删除后不可恢复，请谨慎操作',
    );
  };

  // 设置考核版
  handleSetAssessment = () => {
    const self = this;
    const { version } = self.props.match.params;
    showConfirm(
      () => {
        self.setState({ assessmentLoading: true });
        api.assessmentUsingGET({ params: { versionId: version } }).then(result => {
          if (result && result.code === 1) {
            message.loading('设置考核版标签中', 2, () => {
              self.getVersionsList(self.props);
            });
          }
          self.setState({ assessmentLoading: false });
        });
      },
      '设置考核版标签',
      '确定将此版本设置为考核版吗？',
    );
  };

  /**
   * @Descripttion: 设置预算版
   * @param {*}
   * @return {*}
   */
  handlersetBudgetVersion = async () => {
    const response = await commonBudgetVersion({});
    let content = `非预算季时，复制为${moment().year()}年定稿版预算版`;
    if (response?.code === 1) {
      if (!_.isEmpty(response.data)) {
        content = `确认后将基于（${response.data}）手动设置预算版本。`;
      }
      showConfirm(
        () => {
          this.setState({
            setBudgetLoading: true,
          });
          // 请求手动设置预算版本
          api
            .copyBudgetVersion({
              params: {
                versionId: this.props.match.params.version,
              },
            })
            .then(res => {
              if (res.code === 1 && res.data === 'ok') message.success('设置成功', 1);
            })
            .then(() => {
              this.setState({
                setBudgetLoading: false,
              });
            });
        },
        '手动设置预算版本',
        content,
      );
    }
  };

  /**
   * @Descripttion: 复制预算版
   * @param {*}
   * @return {*}
   */
  handlercopyBudgetVersion = async () => {
    const self = this;
    const response = await commonBudgetVersion({});
    let content = `非预算季时，复制为${moment().year()}年定稿版预算版`;
    if (response?.code === 1) {
      if (!_.isEmpty(response.data)) {
        content = `确认后将基于（${response.data}）手动复制预算版本。`;
      }
      showConfirm(
        () => {
          this.setState({
            setBudgetLoading: true,
          });
          // 请求手动设置预算版本
          api
            .copyReturnPlanVersion({
              params: {
                versionId: this.props.match.params.version,
              },
            })
            .then(res => {
              if (res.code === 1 && res.data === 'ok') {
                self.getVersionsList(self.props);
              }
            })
            .then(() => {
              this.setState({
                setBudgetLoading: false,
              });
            });
        },
        '手动复制预算版本',
        content,
      );
    }
  };

  // 弹出待办框
  getStayToThingId = item => {
    const { visible } = this.state;
    this.setState({
      visible: !visible,
      toDoItem: [item],
    });
  };

  // 关闭待办框
  handleCancel = () => {
    const { visible } = this.state;
    this.setState({
      visible: !visible,
      toDoItem: [],
    });
  };

  // 发起审批
  handleStartApproval = () => {
    const { project } = this.props.match.params;
    api.approvedCheckUsingGET_2({ params: { projectId: project } }).then(res => {
      if (res && res.code === 1 && res.data) {
        message.loading('发起审批中', 2, () => {
          const url = `${window.location.origin}/#/common/ReturnMoneyPlanApprove?action=modify&projectId=${project}`;
          handlerMatomoEvent({
            category: 'Page',
            action: '回款计划-回款审批',
            name: '回款计划-回款审批',
          });
          window.open(url);
        });
      }
    });
  };

  // 导出版本
  handleExportReportForm = () => {
    const { match } = this.props;
    const params = {
      versionId: match.params.version,
    };
    const sessionToken = localStorage.getItem('sessionToken');
    const exportQueryString = qs.stringify({ ...params, sessionToken });
    window.open(
      `${process.env.apiUrl}/api/v1/returnPlan/returnPlanVersionExport?${exportQueryString}`,
    );
  };

  // 查看审批
  handlerViewApproved = () => {
    const self = this;
    const { version } = self.props.match.params;
    self.setState({ deleteLoading: true });
    const parameters = {
      versionId: version,
    };
    apis.goodsApprovedViewUsingGET({ params: parameters }).then(data => {
      if (data && data.code * 1 === 1 && data.data.status * 1 === 1) {
        window.open(`${data.data.url}`);
      }
    });
  };

  render() {
    const {
      dispatch,
      expandedRowKeys,
      treeData,
      match,
      versionsList,
      overAllYears,
      currentYear,
      currentMonths,
    } = this.props;
    const { level1, level2, project, stage, category, version } = match.params;
    const {
      unusualLoading,
      createLoading,
      deleteLoading,
      assessmentLoading,
      viewApprovedLoading,
      setBudgetLoading,
      visible,
      toDoItem,
      agentInfo,
    } = this.state;
    const attribute = {
      // wrapClassName: styles.aletratinon,
      title: '版本变动消息提醒',
      width: '90%',
      height: '50%',
      visible,
      centered: true,
      onCancel: () => this.handleCancel(),
      footer: (
        <>
          <AuthorizedButton authority="business_returnMoneyPlan_createVersion">
            <Button type="primary" onClick={this.handlerCreate} disabled={!visible}>
              创建版本
            </Button>
          </AuthorizedButton>
          <Button onClick={() => this.handleCancel()}>关闭</Button>
        </>
      ),
    };
    // 数据加载完成再加载表格
    const IS_DATA =
      currentYear &&
      currentMonths &&
      !_.isEmpty(versionsList) &&
      !_.isEmpty(treeData) &&
      !_.isEmpty(version);
    let titleTree = null;
    let fixedColumns = null;
    if (IS_DATA) {
      // console.log(this.props, 'this.props')
      const currentVersion = _.last(_.filter(versionsList, x => x.versionId === version));
      titleTree = getTitleTree(currentYear, currentMonths, currentVersion);
      fixedColumns = getFixedColumns(currentYear, currentMonths, match, currentVersion);
    }
    return (
      <PageHeaderWrapper
        className="page-header"
        breadcrumb={null}
        title={<ProjectsPath menu="SupplyPlan" {...this.props} />}
        tags={<CurrentStage {...this.props} />}
        extra={<PageExtra {...this.props} handleStartApproval={this.handleStartApproval} />}
      >
        <Card className="page-header-card">
          {visible ? (
            <Modal {...attribute}>
              <span>{`[${toDoItem[0].todoType}]${toDoItem[0].content}`}</span>
            </Modal>
          ) : null}
          <Tabs
            size="large"
            animated={false}
            onChange={key => {
              router.replace(
                `/OperatingPlan/ReturnMoneyPlan/${level1}/${level2}/${project}/${stage}/${key}`,
              );
            }}
            activeKey={category}
            tabBarExtraContent={
              <div style={{ display: 'flex' }}>
                {!_.isEmpty(agentInfo) && (
                  <TextScroll
                    agentInfo={agentInfo}
                    getStayToThingId={v => this.getStayToThingId(v)}
                  />
                )}
                <TabBarExtraContent
                  {...this.props}
                  handlerUnusualCreate={this.handlerUnusualCreate} // 异常创建
                  handlerCreate={this.handlerCreate} // 新建版本
                  unusualLoading={unusualLoading} // 异常创建loading
                  createLoading={createLoading} // 新建版本loading
                />
              </div>
            }
          >
            <Tabs.TabPane tab="月度动态版" key="dynamic" />
            <Tabs.TabPane tab="预算版" key="budget" />
            <Tabs.TabPane tab="战规版" key="strategy" />
            <Tabs.TabPane tab="投资版" key="investment" />
          </Tabs>
          {/* 是否有版本列表 */}
          {!_.isEmpty(versionsList) && (
            <PageTop
              deleteLoading={deleteLoading}
              handlerDelete={this.handlerDelete}
              assessmentLoading={assessmentLoading}
              handleSetAssessment={this.handleSetAssessment}
              handleExportReportForm={this.handleExportReportForm}
              viewApprovedLoading={viewApprovedLoading}
              handlerViewApproved={this.handlerViewApproved}
              handlersetBudgetVersion={this.handlersetBudgetVersion}
              handlercopyBudgetVersion={this.handlercopyBudgetVersion}
              setBudgetLoading={setBudgetLoading}
              {...this.props}
            />
          )}
          {/* 表格是否处理完数据并且有版本 */}
          {IS_DATA ? (
            <BaseTable
              subtractHeight="210px"
              defaultExpandedRowKeys={expandedRowKeys}
              expandColumnKey="name"
              headerHeight={[30, 30, 30, 30, 30]}
              fixedColumns={fixedColumns}
              headerRenderer={headerRenderer(titleTree, currentYear, overAllYears, dispatch)}
              treeData={treeData}
            />
          ) : (
            <PageEmpty emptyTitle={this.state.emptyMsg} />
          )}
        </Card>
      </PageHeaderWrapper>
    );
  }
}
